/*
 * @Description:
 * @Author: jun.wu
 * @Date: 2022-09-21 14:17:01
 * @LastEditors: jun.wu
 * @LastEditTime: 2022-10-25 14:21:08
 */
import store from "@/store";
import axios from "axios";
import router from "@/router";
import { Message } from "element-ui";
import { getTimeStamp } from "@/utils/auth";

const TimeOut = 3600; //一小时

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 50000, //设置超时
});
// 请求拦截器
service.interceptors.request.use(
  (config) => {
    //统一注入token
    //config是请求的配置信息（必须要返回的）
    if (store.getters.token) {
      //当token存在的时候，检查时间戳是否超时
      if (IsCheckTimeOut()) {
        store.dispatch("user/logout"); //登出操作
        router.push("/login"); //跳转登录页
        return Promise.reject(new Error("token超时"));
      }
      config.headers["Authorization"] = `Bearer ${store.getters.token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 响应拦截器
service.interceptors.response.use(
  (response) => {
    //axios默认加了一层data
    const { success, message, data } = response.data;
    if (success) {
      return data;
    } else {
      Message.error(message);
      return Promise.reject(new Error(message));
    }
  },
  (error) => {
    //被动检测token失效
    //error信息里有response的对象
    if (
      error.response &&
      error.response.data &&
      error.response.data.code == 10002
    ) {
      // 当code为10002时
      store.dispatch("user/logout");
      router.push("/login");
    } else {
      Message.error(error.message); //提示错误信息
    }
    return Promise.reject(error);
  }
);
//是否超时
function IsCheckTimeOut() {
  var currentTime = Date.now(); //当前时间戳
  var timeStamp = getTimeStamp(); //缓存时间戳
  return (currentTime - timeStamp) / 1000 > TimeOut;
}
export default service;
